import { O2mTree } from './view/o2mtree.js'
import { O2mForm } from './view/o2mform.js'

import { fields_helper } from './node_helper.js'

export class RelationNode {
  constructor(node, payload = {}) {
    const { rpc, models } = payload

    this._models_in_config = models
    this._node = node
    this._rpc = rpc
    const { meta } = this.node
    this.relation = this.env.one2many(meta, { context: this.context })
  }

  get node() {
    return this._node
  }

  get rpc() {
    return this._rpc
  }

  get env() {
    return this.rpc.env
  }

  get views() {
    return this.node.views || {}
  }

  get models_in_config() {
    return this._models_in_config
  }
  get fields_in_config() {
    // 这是 配置文件中 的定义

    const in_config = this.node.fields || {}
    const in_sheet = fields_helper.fields_get_in_views(this.views)

    const fs = fields_helper.merge_fields(in_config, in_sheet)

    return fs
  }

  get context() {
    const { context = {} } = this.node
    return context
  }

  get metadata() {
    const { meta } = this.node
    return meta.metadata
  }

  get model() {
    const { meta } = this.node
    return meta.relation
  }

  get Model() {
    return this.env.model(this.model, { metadata: this.node.meta.metadata })
  }

  _get_view(view_type, ViewClass) {
    const config = this.views[view_type] || {}
    return new ViewClass({ relation_node: this, config })
  }

  get tree() {
    return this._get_view('tree', O2mTree)
  }

  get form() {
    return this._get_view('form', O2mForm)
  }

  async load_select_options(kwargs = {}) {
    // console.log(kwargs, this.node)
    const { meta, domain = [], fields: fields1 = {} } = this.node
    const rel = this.env.relation({ ...meta, domain })
    const { current = 1, pageSize: limit = 8, fields: fields2 = {} } = kwargs

    const current2 = current < 1 ? 1 : current
    const offset = (current2 - 1) * limit

    const fields = { ...fields1, ...fields2 }

    const res = await rel.load_select_options({
      ...kwargs,
      offset,
      limit,
      fields
    })
    const { length, records } = res

    return {
      current: current2,
      pageSize: limit,
      total: length,
      records
    }
  }

  remove_one(row, { records, values }) {
    // console.log('remove_one', row, records, values)

    const Rel = this.relation
    Rel.set_edit({ records, values })
    const res = Rel.remove_one(row.id)
    const records_edit = Rel.records_edit
    return records_edit
  }
}
